let _vue = null;

export default class vueRouter {
    constructor (options) {
        this.options = options;
        this.mode = options.mode || 'hash'
        this.routeMap = {};
        // 响应式对象
        this.data = _vue.observable({
            current: '/' // 当前路由地址
        })
    }
    static install (Vue) {
        // 1.判断当前插件是否已经被安装
        if (vueRouter.install.installed) return;
        vueRouter.install.installed = true;
        // 2.把Vue构造函数记录到全局变量
        _vue = Vue;
        // 3.将创建Vue实例时传入的router对象注入到Vue实例上
        // 混入
        Vue.mixin({
            beforeCreate () {
                if (this.$options.router) {
                    _vue.prototype.$router = this.$options.router;
                    this.$options.router.init();
                }
            }
        });
    }
    init () {
        this.initRouteMap();
        this.initEvent();
        this.initComponents(_vue);
    }
    initRouteMap () {
        // 遍历所有的路由规则routes,把routes解析成键值对的形式存储到routeMap中
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component;
        });
    }
    // <router-link to='/'></router-link>
    initComponents (Vue) {
        const self = this;
        Vue.component('router-link', {
            props: {
                to: String
            },
            // template: '<a :href="to"><slot></slot></a>'
            render (h) { // h()创建虚拟DOM
                return h('a', {
                    attrs: {
                        href: self.mode === 'hash' ? '#' + this.to : this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [this.$slots.default]);
            },
            methods: {
                clickHandler (e) {
                    if (self.mode === 'history') {
                        e.preventDefault();
                        history.pushState({}, '', this.to);
                    }
                    this.$router.data.current = this.to;
                }
            }
        });

        Vue.component('router-view', {
            render (h) {
                // 根据当前路径找到对应的组件
                const component = self.routeMap[self.data.current];
                return h(component);
            }
        });
    }
    initEvent () {
        if (this.mode === 'history') {
            window.addEventListener('popstate', () => {
                this.data.current = window.location.pathname;
            });
        }
        if (this.mode === 'hash') {
            window.addEventListener('load', () => {
                this.data.current = window.location.hash.substr(1);
                if (!this.data.current) {
                    this.data.current = '/';
                    window.location.hash = '#/';
                };
            });
            window.addEventListener('hashchange', () => {
                this.data.current = window.location.hash.substr(1);
            });
        }
    }
}